layui.use(['table', 'jquery', 'form', 'admin'], function () {
    let table = layui.table,
        $ = layui.jquery,
        form = layui.form,
        admin = layui.admin;
    if (!localStorage.getItem('Authorization')) {
        layer.alert('请先登录', {
            skin: 'layui-layer-molv' //样式类名  自定义样式
            , closeBtn: 0    // 是否显示关闭按钮
            , anim: 1 //动画类型
            , btn: ['返回主页'] //按钮
            , icon: 6    // icon
            , yes: function () {
                location.href = '/'
            }
        });
    } else {
        let content = ""
        let testEditor;

        let listAllClassify = $.ajax({
            type: "GET",
            url: '/api/article/listAllClassify',
            dataType: 'json',
            data: {},
            success: function (data) {
                if (data.status === 200) {
                    data = data.data
                    let html = ""
                    for (let i = 0; i < data.length; ++i) {
                        let text = '<option value="' + data[i].id + '">' + data[i].name + '</option>'
                        html += text
                    }
                    $('#checkedLevel').html(html)
                } else {
                    layer.msg(data.msg)
                }
            },
            err: function () {
                layui.use('layer', function () {
                    layer.msg("服务器请求失败")
                });
            }
        });

        $.when(listAllClassify).done(function () {
            let getOneArticle = $.ajax({
                type: "GET",
                url: '/api/article/getOneArticle',
                dataType: 'json',
                data: {
                    id: getUrlParam('id')
                },
                success: function (data) {
                    if (data.status === 200) {
                        content = data.data.content
                        console.log(data.data.title)
                        $('#title').val(data.data.title)
                        $("#checkedLevel").find('option[value=' + data.data.classify + ']').attr("selected", true)
                    } else {
                        layer.msg(data.msg)
                    }
                },
                err: function () {
                    layui.use('layer', function () {
                        layer.msg("服务器请求失败")
                    });
                }
            });

            $.when(getOneArticle).done(function () {
                testEditor = editormd("test-editormd", {
                    placeholder: '创享博客支持Markdown编辑，左边编写，右边预览',
                    width: "100%",
                    height: 600,
                    syncScrolling: "single",
                    path: "/static/lib/editormd/lib/",
                    // theme: "dark",//工具栏主题
                    // previewTheme: "dark",//预览主题
                    // editorTheme: "pastel-on-dark",//编辑主题
                    saveHTMLToTextarea: true,
                    emoji: false,
                    taskList: true,
                    tocm: true,                  // Using [TOCM]
                    tex: true,                   // 开启科学公式TeX语言支持，默认关闭
                    flowChart: true,             // 开启流程图支持，默认关闭
                    sequenceDiagram: true,       // 开启时序/序列图支持，默认关闭,
                    // /* 上传图片配置 */
                    imageUpload: true,
                    imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
                    imageUploadURL: "/api/article/upload", //！后端的上传图片服务地址
                    toolbarIcons: function () {  //自定义工具栏
                        return editormd.toolbarModes['full']; // full, simple, mini
                    },
                    markdown: content
                });
            })
        })


        $("#submit").click(function () {
            if ($('#title').val().length < 2 || testEditor.getMarkdown().length < 10) {
                layer.msg('文章过短', function () {
                    return;
                });
            } else {

                $.ajax({
                    type: "POST",
                    url: '/api/article/editArticle',
                    dataType: 'json',
                    headers: {
                        'Authorization': localStorage.getItem('Authorization')
                    },
                    data: {
                        id: getUrlParam('id'),
                        title: $('#title').val(),
                        content: testEditor.getMarkdown(),
                        classify: $('#checkedLevel option:selected').val()
                    },
                    success: function (data) {
                        if (data.status === 200) {
                            layer.msg('修改成功')
                        } else {
                            layer.msg(data.msg)
                        }
                    },
                    err: function () {
                        layui.use('layer', function () {
                            layer.msg("服务器请求失败")
                        });
                    }
                });
            }
        });
    }
});

function getUrlParam(name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    let r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; //返回参数值
}